<template>
  <a-card :bordered="false">
    <!-- 查询区域 -->
    <div class="table-page-search-wrapper">
      <a-form layout="inline" @keyup.enter.native="searchQuery">
        <a-row :gutter="24">
          <a-col :xl="6" :lg="7" :md="8" :sm="24">
            <a-form-item label="员工姓名">
              <a-input placeholder="请输入员工姓名" v-model="queryParam.employeeName"></a-input>
            </a-form-item>
          </a-col>
          <a-col :xl="6" :lg="7" :md="8" :sm="24">
            <a-form-item label="计算日期">
              <a-range-picker
                style="width: 100%"
                v-model="queryParam.calculationDateRange"
                format="YYYY-MM-DD"
                :placeholder="['开始日期', '结束日期']"
              />
            </a-form-item>
          </a-col>
          <a-col :xl="6" :lg="7" :md="8" :sm="24">
            <span class="table-page-search-submitButtons">
              <a-button type="primary" @click="searchQuery" icon="search">查询</a-button>
              <a-button type="primary" @click="searchReset" icon="reload" style="margin-left: 8px">重置</a-button>
            </span>
          </a-col>
        </a-row>
      </a-form>
    </div>

    <!-- 操作按钮区域 -->
    <div class="table-operator">
      <!-- <a-button @click="handleCalculateSalary" type="primary" icon="calculator">计算薪资</a-button> -->
      <a-button @click="handleExport" type="primary" icon="download">导出</a-button>

      <a-divider type="vertical" />

      <!-- 日期快捷选择按钮 -->
      <a-button-group>
        <a-button :type="dateQuickType === 'today' ? 'primary' : 'default'" @click="handleQuickDateSelect('today')">
          当日
        </a-button>
        <a-button :type="dateQuickType === 'week' ? 'primary' : 'default'" @click="handleQuickDateSelect('week')">
          近一周
        </a-button>
        <a-button :type="dateQuickType === 'month' ? 'primary' : 'default'" @click="handleQuickDateSelect('month')">
          近一月
        </a-button>
      </a-button-group>
    </div>

    <!-- table区域-begin -->
    <div>
      <a-table
        ref="table"
        size="middle"
        :scroll="{ x: true }"
        bordered
        rowKey="id"
        :columns="columns"
        :dataSource="dataSource"
        :pagination="ipagination"
        :loading="loading"
        :rowSelection="rowSelection"
        :defaultExpandAllRows="false"
        :expandedRowKeys="expandedRowKeys"
        @expand="onExpand"
        class="j-table-force-nowrap"
        @change="handleTableChange"
      >
        <template slot="htmlSlot" slot-scope="text">
          <div v-html="text"></div>
        </template>
        <template slot="imgSlot" slot-scope="text">
          <span v-if="!text" style="font-size: 12px; font-style: italic">无图片</span>
          <img
            v-else
            :src="getImgView(text)"
            height="25px"
            alt=""
            style="max-width: 80px; font-size: 12px; font-style: italic"
          />
        </template>
        <template slot="fileSlot" slot-scope="text">
          <span v-if="!text" style="font-size: 12px; font-style: italic">无文件</span>
          <a-button v-else :ghost="true" type="primary" icon="download" size="small" @click="downloadFile(text)">
            下载
          </a-button>
        </template>

        <template slot="action" slot-scope="text, record">
          <span v-if="!record.isParent">
            <a @click="handleDetail(record)">详情</a>
            <a-divider type="vertical" />
            <a @click="handleRecalculate(record)">重新计算</a>
          </span>
        </template>
      </a-table>
    </div>

    <!-- 薪资详情弹窗 -->
    <salary-detail-modal ref="salaryDetailModal" @ok="modalFormOk"></salary-detail-modal>

    <!-- 计算薪资弹窗 -->
    <salary-calculation-modal ref="salaryCalculationModal" @ok="modalFormOk"></salary-calculation-modal>
  </a-card>
</template>

<script>
import '@/assets/less/TableExpand.less'
import { mixinDevice } from '@/utils/mixin'
import { JeecgListMixin } from '@/mixins/JeecgListMixin'
import SalaryDetailModal from './modules/SalaryDetailModal'
import SalaryCalculationModal from './modules/SalaryCalculationModal'
import { filterObj } from '@/utils/util'
import moment from 'moment'

export default {
  name: 'SalaryList',
  mixins: [JeecgListMixin, mixinDevice],
  components: {
    SalaryDetailModal,
    SalaryCalculationModal,
  },
  data() {
    return {
      description: '薪资计算记录管理页面',
      // 行选择配置
      rowSelection: {
        selectedRowKeys: [],
        onChange: (selectedRowKeys, selectedRows) => {
          this.selectedRowKeys = selectedRowKeys
          this.selectedRows = selectedRows
        },
      },
      selectedRowKeys: [],
      selectedRows: [],
      expandedRowKeys: [],
      dateQuickType: 'today', // 默认选中当日
      // 表头
      columns: [
        {
          title: '#',
          dataIndex: '',
          key: 'rowIndex',
          width: 60,
          align: 'center',
          customRender: function (t, r, index) {
            return parseInt(index) + 1
          },
        },
        {
          title: '员工姓名',
          align: 'center',
          dataIndex: 'employeeName',
          customRender: function (text, record) {
            return record.isParent ? text : ''
          },
        },
        {
          title: '工种名称',
          align: 'center',
          dataIndex: 'workTypeName',
        },
        {
          title: '完成数量',
          align: 'center',
          dataIndex: 'completedQuantity',
        },
        {
          title: '基础单价',
          align: 'center',
          dataIndex: 'baseRate',
          customRender: function (text) {
            return text ? '¥' + text : ''
          },
        },
        {
          title: '计件薪资',
          align: 'center',
          dataIndex: 'pieceSalary',
          customRender: function (text) {
            return text ? '¥' + text : ''
          },
        },
        {
          title: '协作类型',
          align: 'center',
          dataIndex: 'collaborationType_dictText',
        },
        {
          title: '操作',
          dataIndex: 'action',
          align: 'center',
          fixed: 'right',
          width: 147,
          scopedSlots: { customRender: 'action' },
        },
      ],
      url: {
        list: '/mes/salaryCalculation/getGroupedSalaryData',
        delete: '/mes/salaryCalculation/delete',
        deleteBatch: '/mes/salaryCalculation/deleteBatch',
        exportXlsUrl: '/mes/salaryCalculation/exportXls',
        importExcelUrl: 'mes/salaryCalculation/importExcel',
      },
      dictOptions: {},
      superFieldList: [],
    }
  },
  created() {
    this.getSuperFieldList()
  },
  computed: {
    importExcelUrl: function () {
      return `${window._CONFIG['domianURL']}/${this.url.importExcelUrl}`
    },
  },
  methods: {
    initDictConfig() {},
    getSuperFieldList() {
      let fieldList = []
      fieldList.push({ type: 'string', value: 'employeeName', text: '员工姓名', dictCode: '' })
      fieldList.push({ type: 'string', value: 'employeeNo', text: '员工编号', dictCode: '' })
      fieldList.push({ type: 'string', value: 'workTypeName', text: '工种名称', dictCode: '' })
      fieldList.push({ type: 'int', value: 'completedQuantity', text: '完成数量', dictCode: '' })
      fieldList.push({ type: 'BigDecimal', value: 'baseRate', text: '基础单价', dictCode: '' })
      fieldList.push({ type: 'BigDecimal', value: 'pieceSalary', text: '计件薪资', dictCode: '' })
      fieldList.push({ type: 'int', value: 'collaborationType', text: '协作类型', dictCode: 'collaboration_type' })
      this.superFieldList = fieldList
    },
    handleDetail: function (record) {
      this.$refs.salaryDetailModal.show(record)
      this.$refs.salaryDetailModal.title = '薪资详情'
      this.$refs.salaryDetailModal.disableSubmit = true
    },
    handleCalculateSalary: function () {
      this.$refs.salaryCalculationModal.show()
      this.$refs.salaryCalculationModal.title = '计算薪资'
    },
    handleRecalculate: function (record) {
      let that = this
      this.$confirm({
        title: '确认操作',
        content: '是否确定重新计算该记录的薪资？',
        onOk: function () {
          // 调用重新计算接口
          that.$message.success('重新计算成功')
          that.loadData()
        },
      })
    },
    handleExport: function () {
      if (this.dataSource.length === 0) {
        this.$message.warning('选择有数据的列表才能导出哦！')
        return
      }
      this.$refs.modalForm.exportXls('薪资计算记录')
    },
    getQueryParams() {
      let sqp = {}
      if (this.superQueryParams) {
        sqp['superQueryParams'] = encodeURI(this.superQueryParams)
        sqp['superQueryMatchType'] = this.superQueryMatchType
      }
      var param = Object.assign(sqp, this.queryParam, this.isorter, this.filters)
      param.field = this.getQueryField()
      param.pageNo = this.ipagination.current
      param.pageSize = this.ipagination.pageSize

      // 处理日期范围
      if (this.queryParam.calculationDateRange && this.queryParam.calculationDateRange.length === 2) {
        param.calculationDate_begin = this.queryParam.calculationDateRange[0].format('YYYY-MM-DD')
        param.calculationDate_end = this.queryParam.calculationDateRange[1].format('YYYY-MM-DD')
      }

      return filterObj(param)
    },
    onExpand(expanded, record) {
      if (expanded) {
        this.expandedRowKeys.push(record.id)
      } else {
        this.expandedRowKeys = this.expandedRowKeys.filter((key) => key !== record.id)
      }
    },
    handleEmployeeDetail(record) {
      this.$message.info(`查看员工 ${record.employeeName} 的详细信息`)
    },
    // 重写loadData方法以支持树形数据结构
    loadData(arg) {
      if (!this.url.list) {
        this.$message.error('请设置url.list属性!')
        return
      }
      // 加载数据中
      this.loading = true
      let params = this.getQueryParams() // 查询条件
      let url = this.url.list
      if (this.superQueryFlag) {
        url = this.url.list
      }
      this.$http
        .get(url, { params })
        .then((res) => {
          if (res.success) {
            // 处理树形数据结构
            this.dataSource = this.processTreeData(res.result.records || [])
            this.ipagination.current = res.result.current
            this.ipagination.pageSize = res.result.size
            this.ipagination.total = res.result.total
          }
          this.loading = false
        })
        .catch((error) => {
          console.error('加载数据失败:', error)
          this.loading = false
        })
    },
    processTreeData(data) {
      // 将后端返回的树形数据转换为Ant Design Table需要的格式
      return data.map((item) => {
        if (item.children && item.children.length > 0) {
          return {
            ...item,
            children: item.children,
          }
        }
        return item
      })
    },
    setDateRange(type) {
      let startDate, endDate

      switch (type) {
        case 'today':
          startDate = moment().startOf('day')
          endDate = moment().endOf('day')
          break
        case 'week':
          startDate = moment().subtract(7, 'days').startOf('day')
          endDate = moment().endOf('day')
          break
        case 'month':
          startDate = moment().subtract(1, 'month').startOf('day')
          endDate = moment().endOf('day')
          break
      }

      this.queryParam.calculationDateRange = [startDate, endDate]
      this.dateQuickType = type
      this.loadData(1)
    },
    handleQuickDateSelect(type) {
      this.setDateRange(type)
    },
  },
  mounted() {
    // 初始化默认日期范围为当日
    this.setDateRange('today')
  },
}
</script>
<style scoped>
@import '~@assets/less/common.less';
</style>
